<template>
  <div class="media-display">
    <!-- 图片网格 -->
    <div v-if="images.length > 0" class="image-grid">
      <n-image-group>
        <n-image
          v-for="image in images"
          :key="image.id"
          :src="image.url"
          :width="getImageWidth()"
          :height="getImageHeight()"
          object-fit="cover"
          lazy
          :intersection-observer-options="{
            rootMargin: '50px'
          }"
          @error="handleImageError"
        >
          <template #placeholder>
            <div class="media-placeholder">
              <n-spin size="small" />
              <div>加载中...</div>
            </div>
          </template>
          <template #error>
            <div class="media-error" @click="retryLoadMedia(image)">
              <div>加载失败</div>
              <div class="retry-text">点击重试</div>
            </div>
          </template>
        </n-image>
      </n-image-group>
    </div>

    <!-- 视频网格 -->
    <div v-if="videos.length > 0" class="video-grid">
      <div
        v-for="video in videos"
        :key="video.id"
        class="video-item"
        :style="{ width: getVideoWidth(), height: getVideoHeight() }"
      >
        <!-- 视频预览 -->
        <div class="video-preview" @click="playVideo(video)">
          <video
            :src="video.url"
            :poster="video.poster"
            preload="metadata"
            class="video-element"
            @error="handleVideoError"
          />
          <div class="video-overlay">
            <n-icon size="48" color="white">
              <PlayIcon />
            </n-icon>
            <div class="play-text">播放</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 视频播放模态框 -->
    <n-modal
      v-model:show="videoModalVisible"
      preset="card"
      style="width: 90vw; max-width: 800px"
      :mask-closable="true"
      @update:show="closeVideoModal"
    >
      <div class="video-modal-content">
        <video
          v-if="currentVideo"
          :src="currentVideo.url"
          controls
          autoplay
          class="modal-video"
          @error="handleVideoError"
        />
        <div v-else class="video-error">
          <n-icon size="64" color="#999">
            <AlertCircleIcon />
          </n-icon>
          <div>视频加载失败</div>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useMessage } from 'naive-ui'
import { Play as PlayIcon, AlertCircle as AlertCircleIcon } from '@vicons/ionicons5'
import type { TalkPhoto } from '@/types/talk'

interface Props {
  photos: TalkPhoto[]
  maxDisplay?: number // 最大显示数量
}

const props = withDefaults(defineProps<Props>(), {
  maxDisplay: 9
})

const message = useMessage()
const videoModalVisible = ref(false)
const currentVideo = ref<TalkPhoto | null>(null)

// 分离图片和视频
const images = computed(() => {
  return props.photos
    .filter(photo => isImage(photo))
    .slice(0, props.maxDisplay)
})

const videos = computed(() => {
  return props.photos
    .filter(photo => isVideo(photo))
    .slice(0, props.maxDisplay)
})

// 判断是否为图片
const isImage = (photo: TalkPhoto): boolean => {
  const fileType = photo.fileType?.toLowerCase() || ''
  const url = photo.url?.toLowerCase() || ''

  return fileType.startsWith('image/') ||
         url.includes('.jpg') || url.includes('.jpeg') ||
         url.includes('.png') || url.includes('.gif') ||
         url.includes('.webp') || url.includes('.bmp')
}

// 判断是否为视频
const isVideo = (photo: TalkPhoto): boolean => {
  const fileType = photo.fileType?.toLowerCase() || ''
  const url = photo.url?.toLowerCase() || ''

  return fileType.startsWith('video/') ||
         url.includes('.mp4') || url.includes('.avi') ||
         url.includes('.mov') || url.includes('.wmv') ||
         url.includes('.flv') || url.includes('.webm')
}

// 计算图片尺寸
const getImageWidth = () => {
  const count = images.value.length
  if (count === 1) return 300
  if (count === 2) return 200
  if (count === 3) return 180
  if (count === 4) return 150
  return 120
}

const getImageHeight = () => {
  const count = images.value.length
  if (count === 1) return 300
  if (count === 2) return 200
  if (count === 3) return 180
  if (count === 4) return 150
  return 120
}

// 计算视频尺寸
const getVideoWidth = () => {
  const count = videos.value.length
  if (count === 1) return '100%'
  if (count === 2) return 'calc(50% - 4px)'
  if (count === 3) return 'calc(33.33% - 4px)'
  if (count === 4) return 'calc(50% - 4px)'
  return 'calc(33.33% - 4px)'
}

const getVideoHeight = () => {
  const count = videos.value.length
  if (count === 1) return '300px'
  if (count === 2) return '200px'
  if (count === 3) return '180px'
  if (count === 4) return '150px'
  return '120px'
}

// 播放视频
const playVideo = (video: TalkPhoto) => {
  currentVideo.value = video
  videoModalVisible.value = true
}

// 关闭视频模态框
const closeVideoModal = () => {
  videoModalVisible.value = false
  currentVideo.value = null
}

// 处理图片错误
const handleImageError = (event: Event) => {
  console.warn('图片加载失败:', event)
  message.error('图片加载失败')
}

// 处理视频错误
const handleVideoError = (event: Event) => {
  console.warn('视频加载失败:', event)
  message.error('视频加载失败')
}

// 重试加载媒体
const retryLoadMedia = (media: TalkPhoto) => {
  // 通过添加时间戳参数来强制重新加载
  const timestamp = Date.now()
  const separator = media.url.includes('?') ? '&' : '?'
  const newUrl = `${media.url}${separator}_t=${timestamp}`

  // 更新媒体 URL 来触发重新加载
  media.url = newUrl
  message.info('正在重新加载...')
}
</script>

<style scoped>
.media-display {
  width: 100%;
}

.image-grid {
  display: grid;
  gap: 8px;
  margin-bottom: 16px;
}

.image-grid :deep(.n-image) {
  border-radius: 8px;
  overflow: hidden;
}

.video-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

.video-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.video-preview {
  position: relative;
  width: 100%;
  height: 100%;
  cursor: pointer;
  transition: transform 0.2s;
}

.video-preview:hover {
  transform: scale(1.02);
}

.video-element {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background-color: #000;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.3);
  color: white;
  transition: background-color 0.2s;
}

.video-preview:hover .video-overlay {
  background-color: rgba(0, 0, 0, 0.5);
}

.play-text {
  margin-top: 8px;
  font-size: 14px;
  font-weight: 500;
}

.media-placeholder,
.media-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
  border-radius: 8px;
}

.media-error {
  cursor: pointer;
  transition: background-color 0.2s;
}

.media-error:hover {
  background-color: #e8e8e8;
}

.retry-text {
  font-size: 12px;
  margin-top: 4px;
}

.video-modal-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.modal-video {
  width: 100%;
  max-height: 70vh;
  border-radius: 8px;
}

.video-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  gap: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .image-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  }

  .video-grid {
    gap: 4px;
  }

  .video-item {
    width: calc(50% - 2px) !important;
    height: 150px !important;
  }
}
</style>
